export function generate(ast) {
    const code = generateNode(ast[0]);
    return `return ${code}`;
}

const NodeType = {
    Element: "Element",
    Text: "Text",
    Interpolation: "Interpolation",
};

function generateNode(node) {
    const { type } = node;
    switch (type) {
        case NodeType.Element:
            return generateElement(node);
        case NodeType.Text:
            return generateText(node);
        case NodeType.Interpolation:
            return generateInterpolation(node);
        default:
            break;
    }
}

function generateElement(node) {
    const { tag, children, props } = node;
    const attrs = generateProps(props);
    // const result = children.map((item) => generateNode(item));
    // const context = result.length == 1 ? result.join(",") : `[${result.join(",")}]`;
    if (children.length > 0) {
        return `this._c('${tag}',${attrs},${genreateChildren(children)})`;
    } else {
        return `this._c('${tag}',${attrs}`;
    }
}

function genreateChildren(nodes) {
    if (nodes.length === 1) {
        if (nodes[0].type === NodeType.Text) {
            return generateText(nodes[0], true);
        } else {
            return generateText(nodes[0]);
        }
    } else {
        return `[${nodes.map(generateNode).toString()}]`;
    }
}

function generateProps(props) {
    if (props.length > 0) {
        return `{${props.map((p) => `'${p.name}': '${p.value}'`).join(",")}}`;
    } else {
        return null;
    }
}

function generateText(node, isText = false) {
    return isText ? `'${node.content}'` : `this._v('${node.content}')`;
    // return `'${node.content}'`;
}

function generateInterpolation(node) {
    return `this.${node.content.content}`;
    // const { tag, props, children } = node;
    // const attrs = generateProps(props);
    // const context = getContentByType(children, NodeType.Interpolation);
    // return `return this.c('${tag}', ${ attrs }, this.${ context })`;
}
